package cn.tqfeiyang.smartadmin.commons.security;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * 内存的用户加载器
 *
 * @author tqfeiyang
 * @since 2024/10/16 11:46
 */
@Service
@ConditionalOnMissingBean(value = IUserLoader.class)
public class MemoryUserLoader implements IUserLoader {

    private static List<UserDetails> knownUserLists;

    static {
        knownUserLists = new ArrayList<>();

        // 管理用户 admin
        UserDetails adminUser = new UserDetails();
        adminUser.setUserId(1L);
        adminUser.setUsername("admin");
        adminUser.setNickname("管理用户");
        adminUser.setEmail("admin@localhost.com");
        adminUser.setAdmin(true);
        knownUserLists.add(adminUser);

        // 测试用户 test
        UserDetails testUser = new UserDetails();
        testUser.setUserId(2L);
        testUser.setUsername("test");
        testUser.setNickname("测试用户");
        testUser.setEmail("test@localhost.com");
        testUser.setAdmin(false);
        knownUserLists.add(testUser);
    }

    /**
     * 根据用户账号查找用户详情
     *
     * @param username 用户账号、也可以是电子邮件或者手机号
     * @return 用户详情，如果找不到则返回null
     */
    @Override
    public UserDetails findUserDetails(String username) {
        Assert.notNull(username, "username不能为空");
        return knownUserLists.stream()
                .filter(userDetails -> {
                    return username.equalsIgnoreCase(userDetails.getUsername())
                            || username.equalsIgnoreCase(userDetails.getEmail())
                            || username.equalsIgnoreCase(userDetails.getPhone());
                })
                .findFirst().orElse(null);
    }

    /**
     * 根据用户id查找用户详情
     *
     * @param userId 用户id
     * @return 用户详情，如果找不到则返回null
     */
    @Override
    public UserDetails findUserDetails(Long userId) {
        Assert.notNull(userId, "userId不能为空");
        return knownUserLists.stream()
                .filter(userDetails -> {
                    return userId.equals(userDetails.getUserId());
                })
                .findFirst().orElse(null);
    }
}
